//
//  LJRefreshView.swift
//  LJWeibo
//
//  Created by Raymond on 15/12/23.
//  Copyright © 2015年 liu. All rights reserved.
//

import UIKit

class LJRefreshControl: UIRefreshControl {
    /// MARK: - 属性
    private let refreshControlOffsetY:CGFloat = -60
    private var isUp = false
    
    override var frame: CGRect {
        didSet{
            if frame.origin.y > 0 {
                return
            }
            // 判断是否正在刷新
            if refreshing {
                refreshView.startLoading()
            }
            if frame.origin.y < refreshControlOffsetY && !isUp {
                isUp = !isUp
                refreshView.rotationArrowIcon(isUp)
            }else if frame.origin.y > refreshControlOffsetY && isUp {
                isUp = !isUp
                refreshView.rotationArrowIcon(isUp)
            }
            
        }
    }
    
    override func endRefreshing() {
        super.endRefreshing()
        
        refreshView.endLoading()
    }
    
    override init() {
        super.init()
        prepareUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 准备UI
    func prepareUI() {
        addSubview(refreshView)
        refreshView.ff_AlignInner(type: ff_AlignType.CenterCenter, referView: self, size: refreshView.bounds.size)
    }
    
    /// MARK: - 懒加载
    private var refreshView = LJRefreshView.refreshView()
}

class LJRefreshView: UIView {

    /// 属性
    /// 箭头视图
    @IBOutlet weak var arrowView: LJRefreshView!
    /// 箭头图标
    @IBOutlet weak var arrowIcon: UIImageView!
    /// 圈圈图标
    @IBOutlet weak var loadingIcon: UIImageView!
    // 从xib中加载控件
    class func refreshView() -> LJRefreshView{
        let view = NSBundle.mainBundle().loadNibNamed("LJRefreshView", owner: nil, options: nil).last as! LJRefreshView
        return view
    
    }
    // 旋转箭头
    func rotationArrowIcon(isUp: Bool) {
        UIView.animateWithDuration(0.25) { () -> Void in
            self.arrowIcon.transform = isUp ? CGAffineTransformMakeRotation(CGFloat(M_PI - 0.0001)) : CGAffineTransformIdentity
        }
    }
    // 旋转圈圈
    func startLoading() {
        let animKey = "animKey"
        // 判断动画是否在执行
        if loadingIcon.layer.animationForKey(animKey) != nil {
            return
        }
        // 隐藏箭头视图
        arrowView.hidden = true
        // 创建核心动画
        let anim = CABasicAnimation(keyPath: "transform.rotation")
        anim.toValue = 2 * M_PI
        anim.duration = 0.5
        anim.repeatCount = MAXFLOAT
        // 设置不移除
        anim.removedOnCompletion = false
        // 添加
        loadingIcon.layer.addAnimation(anim, forKey: animKey)
        
    }
    
    // 停止动画
    func endLoading() {
        arrowView.hidden = false
        loadingIcon.layer.removeAllAnimations()
    }

}
